package com.chagee.store.operation.server.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chagee.store.operation.common.enums.LarkMessageTypeEnum;
import com.chagee.store.operation.server.entity.StoreConfigurationDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.dao.StoreConfigurationMapper;
import com.chagee.store.operation.server.event.service.*;
import com.chagee.store.operation.server.model.bo.OrderTakingExcelBO;
import com.chagee.store.operation.server.model.info.LarkMessageInfo;
import com.chagee.store.operation.server.service.WorkOrderAcceptanceService;
import com.chagee.store.operation.server.service.biz.FeiShuMessageBizService;
import com.chagee.store.operation.server.service.biz.TaskExecutionBizService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 推送未接单门店清单
 */
@Component
@Slf4j
public class PushMissedOrderMsgJobHandler {

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;

	@Resource
	private WorkOrderAcceptanceService workOrderAcceptanceService;

	@Resource
	private FeiShuMessageBizService feiShuMessageBizService;

	/**
	 * 推送未接单门店清单  0 0 3 * * ?
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("pushMissedOrderMsgHandler")
	public ReturnT<String> pushMissedOrderMsg(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = DateUtil.timer();
		log.info("推送未接单门店清单定时任务开始,traceId :{}", span.getTraceId());
		try {
			List<WorkOrderDO> result = new ArrayList<>();
			long startIndex = 0L;
			while (true) {
				List<WorkOrderDO> workOrderDOList = workOrderBaseService.selectByPendingOrders(startIndex);
				if (CollectionUtils.isEmpty(workOrderDOList)) {
					break;
				}
				result.addAll(workOrderDOList);
				startIndex = Math.toIntExact(workOrderDOList.stream().map(WorkOrderDO::getId).max(Comparator.naturalOrder()).orElse(0L));
			}
			log.info("推送未接单门店清单 :{}", JSON.toJSONString(result));

			if (CollectionUtils.isEmpty(result)) {
				return ReturnT.SUCCESS;
			}

			Map<String, List<OrderTakingExcelBO>> stringListMap = result.stream().map(s ->
				new OrderTakingExcelBO().setStoreNo(s.getStoreCode()).setStoreName(s.getStoreName()).setCompanyName(s.getCompanyName())
			).filter(s -> StringUtils.isNotBlank(s.getCompanyName())).collect(Collectors.groupingBy(OrderTakingExcelBO::getCompanyName));

			List<Object> columns = feiShuMessageBizService.buildColumns(OrderTakingExcelBO.class);
			for (Map.Entry<String, List<OrderTakingExcelBO>> entry : stringListMap.entrySet()) {
				OrderTakingExcelBO excelBO = entry.getValue().get(0);
				LarkMessageInfo info = new LarkMessageInfo();
				info.setStoreNo(excelBO.getStoreNo());
				info.setCompanyName(entry.getKey());
				info.setColumns(columns);
				List<Object> rows = Arrays.asList(entry.getValue().toArray());
				info.setRows(rows);
				info.setType(LarkMessageTypeEnum.orderTakingNotice.getType());
				try {
					feiShuMessageBizService.sendMessage2(info);
					log.info("子公司{}发送飞书通知成功:", entry.getKey());
				} catch (Exception e) {
					log.error("子公司{}发送飞书通知失败:", entry.getKey(), e);
				}
			}

		} catch (Exception e) {
			XxlJobLogger.log("推送未接单门店清单定时任务异常，异常信息:", e);
			log.error("推送未接单门店清单定时任务异常 => param : {} => 异常信息 :", param, e);
		}
		XxlJobLogger.log("推送未接单门店清单定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		return ReturnT.SUCCESS;
	}
}
